/**
 * Copyright 2020-2030 Jinhui Technology Co. LTD  All Rights Reserved.
 */
package jgl.vajra.operator.widget.retrofithelper.utils;

import android.text.TextUtils;
import android.util.Base64;

import com.orhanobut.logger.Logger;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

import jgl.vajra.operator.widget.manager.SPManager;

/**
 * . <br>
 *
 * @author nongkegai<br>
 * @version <br>
 * @date Create in 2021/7/2 9:54 <br>
 * @description 1.0 <br>
 */


public class AEACCoder {

    static final String ALGORITHM = "AES";
    static Charset charset = Charset.forName("UTF-8");
    private static byte[] seedbyte = "0#d瑳8c(db쮘f8bf)cf놿4d!3a@93.26d^ce0꾔29$37좺3+c쮘6a".getBytes(StandardCharsets.UTF_8);
    private static final String randomType = "SHA1PRNG";

    /**
     * 生成密钥
     *
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String generateKey() {
        byte[] bytes;
        try {
            KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM);
            //SecureRandom random = new SecureRandom(randomType);
            SecureRandom random = SecureRandom.getInstance(randomType);
            random.setSeed(seedbyte);
            kg.init(256, random);
            SecretKey secretKey = kg.generateKey();
            bytes = keypairToBin(secretKey);
        } catch (Exception e) {
            bytes = null;
        }
        if (bytes == null) bytes = "".getBytes(StandardCharsets.UTF_8);
        String s = Base64.encodeToString(bytes, Base64.NO_WRAP);
        Logger.d(s + "生成秘钥");
        return s;
    }

    // 加密
    public static String encrypt(String content) {
        if (TextUtils.isEmpty(content)){
            return "";
        }
        return Base64.encodeToString(aes(content.getBytes(charset), Cipher.ENCRYPT_MODE, SPManager.HomeData.getRASPrivateKey()), Base64.NO_WRAP);
    }

    // 解密
    public static String decrypt(String content) {
        if (TextUtils.isEmpty(content)){
            return "";
        }
        byte[] contentArray = Base64.decode(content, Base64.NO_WRAP);
        byte[] result = aes(contentArray, Cipher.DECRYPT_MODE, SPManager.HomeData.getRASPrivateKey());
        return new String(result, charset);

    }

    private static byte[] aes(byte[] contentArray, int mode, String keyStr) {
        // String keyStr = generateKey();
        byte[] result = null;
        try {
            SecretKey secretKey = AEACCoder.binToSecretKey(Base64.decode(keyStr, Base64.NO_WRAP));
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            //Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(mode, secretKey);
            result = cipher.doFinal(contentArray);
        } catch (Exception e) {
            e.printStackTrace();
            Logger.d(e.getMessage() + "失败");
        }
        if (result == null) result = "".getBytes(StandardCharsets.UTF_8);
        return result;
    }

    private static byte[] keypairToBin(SecretKey kp) {
        try (ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream oout = new ObjectOutputStream(bout);) {
            oout.writeObject(kp);
            return bout.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static SecretKey binToSecretKey(byte[] data) {
        try (ByteArrayInputStream b = new ByteArrayInputStream(data); ObjectInputStream o = new ObjectInputStream(b);) {
            Object obj = o.readObject();
            return (SecretKey) obj;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
